package com.icode.web.controller.User;

import com.icode.core.dto.user.PasswordHandelDTO;
import com.icode.core.dto.user.UserDTO;
import com.icode.core.model.user.User;
import com.icode.core.shared.MailHandle;
import com.icode.core.shared.SecurityUtil;
import com.icode.core.shared.ValidateNumHandle;
import com.icode.service.user.MessageService;
import com.icode.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.mail.MessagingException;
import javax.validation.Valid;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: lb
 * Date: 15-12-9
 * Time: 下午6:03
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/password")
public class PasswordHandleController {

    @Autowired
    private UserService userService;

    @Autowired
    private MessageService messageService;

    @RequestMapping(value = "forget/form", method = RequestMethod.GET)
    public ModelAndView forgetPassWord() {
        return new ModelAndView("front/user/resetting", "passwordHandelDTO", new PasswordHandelDTO());
    }

    @RequestMapping(value = "forget/form", method = RequestMethod.POST)
    private String submitForm(PasswordHandelDTO passwordHandelDTO) {
        String userName = passwordHandelDTO.getUserName();
        String validationNum = passwordHandelDTO.getValidationNum();
        Map<String, Object> getValidateNum = ValidateNumHandle.getValidateNum();
        if (getValidateNum.size() <= 0) {
            return "redirect:/password/forget/form";
        }
        String validationnum = getValidateNum.get(userName).toString().substring(0, 4);
        if (validationnum.equals(validationNum)) {
            userService.updataPassWord(passwordHandelDTO);
            messageService.removePhoneNum(passwordHandelDTO.getUserName());
            return "redirect:/login/form";
        } else {
            return "redirect:/password/forget/form";
        }
    }

    @RequestMapping(value = "update/from", method = RequestMethod.GET)
    public ModelAndView toupdatapassword() {
        User user = SecurityUtil.currentUser();
        PasswordHandelDTO passwordHandelDTO = PasswordHandelDTO.toDTO(user);
        return new ModelAndView("front/user/upDataPassWord", "passwordHandelDTO", passwordHandelDTO);
    }

    @RequestMapping(value = "update/from", method = RequestMethod.POST)
    public String updatapassword(@ModelAttribute(value = "passwordHandelDTO") @Valid PasswordHandelDTO passwordHandelDTO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return "front/user/upDataPassWord";
        }
        userService.updataPassWord(passwordHandelDTO);
        return "redirect:/login/form";
    }

}
